import pymysql


# 数据库的工具类
class DBUtil:
    # 定义类属性
    conn = None

    # 数据库链接
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                                   database="ihrm", charset="utf8")
        pass

    # 数据库关闭
    @classmethod
    def __close_db(cls):
        cls.conn.close()
        pass

    # 查询
    @classmethod
    def query_db(cls, sql):
        cursor = None
        result = None
        try:
            cls.__connect_db()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            result = cursor.fetchone()

        except Exception as error:
            print("读取数据库报错：", error)
            pass
        cursor.close()
        cls.__close_db()

        return result
        pass

    # 增删改
    @classmethod
    def update_db(cls, sql):
        cursor = None
        try:
            cls.__connect_db()
            cursor = cls.conn.cursor()
            cursor.execute(sql)
            rows = cls.conn.affected_rows()
            cls.conn.commit()
        except Exception as error:
            print("更新数据库报错：", error)
            cls.conn.rollback()
            pass
        cursor.close()
        cls.__close_db()
        pass


if __name__ == '__main__':
    result1 = DBUtil.query_db('select * from t_book')
    print(result1)
    result2 = DBUtil.update_db("delete from t_book where title like '%三%'")
